package com.yolo.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yolo.common.annotation.Log;
import com.yolo.common.enums.BusinessType;
import com.yolo.entity.OperLog;
import com.yolo.entity.dto.OperLogDto;
import com.yolo.service.OperLogService;
import com.yolo.util.Result;
import com.yolo.util.YoluoTools;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 操作日志记录
 * </p>
 *
 * @author 霜蟾
 * @since 2021-04-25
 */
@RestController
@RequestMapping("/log")
@CrossOrigin
public class OperLogController {

    @Autowired
    private OperLogService operLogService;

    @GetMapping("/get/{id}")
    public Result getOperLog(@PathVariable("id") int operId) {
        OperLog operLog = operLogService.getById(operId);
        return Result.succ(operLog);
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteOperLog(@PathVariable("id") int operId) {
        operLogService.removeById(operId);
        return Result.succ(null);
    }

    @DeleteMapping("/batchDelete/{operid}")
    public Result batchDeleteOperLog(@PathVariable("operid") String operIds) {
        operLogService.removeByIds(Arrays.asList(operIds.split(",")));
        return Result.succ(null);
    }

    @DeleteMapping("/clean")
    @Log(title = "日志模块", businessType = BusinessType.CLEAN)
    public Result deleteFromOperLog() {
        operLogService.delteForm();
        return Result.succ(null);
    }

    @GetMapping("/list")
    public Result selectPageOperLog(OperLogDto log) {
        Page<OperLog> page = new Page<>(log.getPageIndex(), log.getPageSize());
        QueryWrapper qw = new QueryWrapper();
        qw.orderByDesc("oper_time");
        qw.like("title", log.getTitle());
        qw.like("oper_name", log.getOperName());
        if (log.getBusinessType() != null && !log.getBusinessType().equals("")) {
            qw.eq("business_type", log.getBusinessType());
        }
        if (log.getStatus() != null && !log.getStatus().equals("")) {
            qw.eq("status", log.getStatus());
        }
        if (log.getBeginTime() != null && !log.getBeginTime().equals("")) {
            qw.between("oper_time", log.getBeginTime(), log.getEndTime());
        }
        Page<OperLog> page1 = operLogService.page(page, qw);
        return Result.succ(MapUtil.builder()
                .put("count", page1.getTotal())
                .put("data", page1.getRecords())
                .put("limits", page1.getPages()).map());
    }

    @Log(title = "日志模块", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void exportOperLog(HttpServletResponse response) {
        try {
            List<OperLog> list = operLogService.list();
            @SuppressWarnings("resource")
            HSSFWorkbook wb = new HSSFWorkbook();
            //HSSFCellStyle style = ExcelStyleUtil.getStyle(wb);
            HSSFSheet sheet = wb.createSheet("记录");
            HSSFRow row;
            int columnIndex = 0;
            row = sheet.createRow(0);
            row.setHeight((short) (22.50 * 10));//设置行高
            row.createCell(columnIndex).setCellValue("序号");
            row.createCell(++columnIndex).setCellValue("日志编号");
            row.createCell(++columnIndex).setCellValue("模块名");
            row.createCell(++columnIndex).setCellValue("业务类型");
            row.createCell(++columnIndex).setCellValue("方法名称");
            row.createCell(++columnIndex).setCellValue("请求方式");
            row.createCell(++columnIndex).setCellValue("操作人员");
            row.createCell(++columnIndex).setCellValue("部门名称");
            row.createCell(++columnIndex).setCellValue("操作地点");
            row.createCell(++columnIndex).setCellValue("请求URL");
            row.createCell(++columnIndex).setCellValue("主机地址");
            row.createCell(++columnIndex).setCellValue("操作状态");
            row.createCell(++columnIndex).setCellValue("错误消息");
            row.createCell(++columnIndex).setCellValue("操作时间");
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                OperLog entity = list.get(i);
                columnIndex = 0;
                row.createCell(columnIndex).setCellValue(i + 1);
                row.createCell(++columnIndex).setCellValue(entity.getOperId());
                row.createCell(++columnIndex).setCellValue(entity.getTitle());
                row.createCell(++columnIndex).setCellValue(YoluoTools.businessTypeFormat(entity.getBusinessType()));
                row.createCell(++columnIndex).setCellValue(entity.getMethod());
                row.createCell(++columnIndex).setCellValue(entity.getRequestMethod());
                row.createCell(++columnIndex).setCellValue(entity.getOperName());
                row.createCell(++columnIndex).setCellValue(entity.getDeptName());
                row.createCell(++columnIndex).setCellValue(entity.getOperLocation());
                row.createCell(++columnIndex).setCellValue(entity.getOperUrl());
                row.createCell(++columnIndex).setCellValue(entity.getDeptName());
                row.createCell(++columnIndex).setCellValue(entity.getOperIp());
                row.createCell(++columnIndex).setCellValue(entity.getStatus());
                row.createCell(++columnIndex).setCellValue(entity.getErrorMsg());
            }
            sheet.setDefaultRowHeight((short) (16.5 * 20));
            //列宽自适应
            for (int i = 0; i <= 11; i++) {
                sheet.autoSizeColumn(i);
            }
            String title = "czjl_all";
            response.setHeader("Content-disposition", "attachment;fileName=" + title + ".xls");
            response.setContentType("application/octet-stream;charset=utf-8");
            OutputStream ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
